package stream;

import org.junit.Test;
import ref.Employee;

import java.util.Arrays;
import java.util.List;
import java.util.Optional;

/**
 * @Author com.alibaba.lizhen
 * @Date 2021/3/24 11:05 上午
 * @Version 1.0
 * @Description
 *  * 创建stream
 *  * 中间操作（过滤、map）
 *  * 终止操作
 */
public class StreamApiTest3 {
    List<Employee> emps = Arrays.asList(
            new Employee(1, "张三1"),
            new Employee(1, "张三1"),
            new Employee(2, "张三2"),
            new Employee(2, "张三2"),
            new Employee(3, "张三3"),
            new Employee(4, "张三4"),
            new Employee(5, "张三5"),
            new Employee(6, "张三6"),
            new Employee(7, "张三7")
    );

    /**
     * Stream 终止操作：
     * 查找 / 匹配
     * allMatch：检查是否匹配所有元素.
     * anyMatch：检查是否至少匹配一个元素
     * noneMatch：检查是否所有元素都不匹配
     * findFirst：返回第一个元素
     * findAny：返回当前流中的任意元素
     * count：返回流中元素的总个数
     * max：返回流中最大值
     * min：返回流中最小值
     * ————————————————
     */
    public enum Status {
        FREE,
        BUSY,
        VOCATION;
    }

    @Test
    public void test5() {
        List<StreamApiTest3.Status> list = Arrays.asList(StreamApiTest3.Status.FREE, StreamApiTest3.Status.BUSY, StreamApiTest3.Status.VOCATION);

        boolean flag1 = list.stream()
                .allMatch((s) -> s.equals(StreamApiTest3.Status.BUSY));
        System.out.println(flag1);

        boolean flag2 = list.stream()
                .anyMatch((s) -> s.equals(StreamApiTest3.Status.BUSY));
        System.out.println(flag2);

        boolean flag3 = list.stream()
                .noneMatch((s) -> s.equals(StreamApiTest3.Status.BUSY));
        System.out.println(flag3);

        // 避免空指针异常
        Optional<StreamApiTest3.Status> op1 = list.stream()
                .findFirst();
        // 如果Optional为空 找一个替代的对象
        StreamApiTest3.Status s1 = op1.orElse(StreamApiTest3.Status.BUSY);
        System.out.println(s1);

//        Optional<Status> op2 = list.stream()
        //并行流
        Optional<StreamApiTest3.Status> op2 = list.parallelStream()
                .findAny();
        System.out.println(op2);

        long count = list.stream()
                .count();
        System.out.println(count);


        //返回最值
        String[] integers = {"1", "2", "3"};
        Optional<Integer> max = Arrays.stream(integers)
                //转为int
                .map(Integer::parseInt)
                //找出最值
                .max(Integer::compareTo);
        System.out.println("max = " + max);
    }


}
